import { createActions, handleActions } from 'redux-actions';
import createNoEffect from '@redux/create-no-effect';
import { loadTagsList } from '@api/tag';
import { get } from 'lodash';

const initState = {
  loadTagsStatus: 'notStart',
  tags: [],
  tagIdsIndexMap: {}
};

const noEffects = createNoEffect(['SET_LOAD_TAGS_STATUS']);

export const actions = createActions({
  LOAD_TAGS: () => dispatch => {
    dispatch(actions.setLoadTagsStatus('pending'));
    return loadTagsList()
      .then(res => {
        dispatch(actions.setLoadTagsStatus('succeed'));
        return Promise.resolve(res);
      })
      .catch(error => {
        dispatch(actions.setLoadTagsStatus('failed'));
        return Promise.reject(error);
      })
      .finally(() => {
        dispatch(actions.setLoadTagsStatus('notStart'));
      });
  },
  ...noEffects.actions
});

const reducer = handleActions(
  {
    LOAD_TAGS: (state, action) => {
      const { error, payload } = action;
      if (error) {
        return state;
      }
      const tags = get(payload, 'data.data.list', []).filter(item => item && item.name.trim());
      const tagIdsIndexMap = tags.reduce((total, current = {}, index) => {
        total[current._id] = index;
        return total;
      }, {});
      return {
        ...state,
        tags,
        tagIdsIndexMap
      };
    },
    ...noEffects.reducers
  },
  initState
);

export default reducer;
